<template>
  <div class="test-view" v-if="isComponentLoaded">
    <component :is="TestForm" ref="moudleRef" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "TestView",
  components: {}
});


import { provide, ref, type DefineComponent, onMounted, onUnmounted } from 'vue';
import type { ModuleInterfaceTest, SendCmd } from "@/common/index";
import { SEND_TEST_CMD_KEY, GET_TEST_DATA_KEY } from "@/common/index";

import { handleCommand } from '@/utils/commandHandler';
import type { AxiosRequestConfig } from 'axios';
import type { Response } from '@/mctp-api';
import signalEvent from "@/utils/signalEvent";

import { useRoute } from "vue-router";
const route = useRoute();

import { LoadModules } from "@/utils/loadModules";

import { useTabsStore } from "@/store/modules/tabs";

// 2. 响应式存储组件（核心）
const TestForm = ref<DefineComponent | null>(null);
let createTestModule: ((sendCmd: SendCmd<any, any>, initialData: any, updateState: (state: any) => void) => ModuleInterfaceTest<any>) | null = null;
const updateState = (state: any) => {
  console.log("更新状态", state);
  useTabsStore().testTaskId = "";
};
const isComponentLoaded = ref(false); // 标记组件是否加载完成，控制模板渲染
interface TestFormInstance {
  dataEvent: (value: any) => void; // 匹配组件的 dataEvent 方法定义
}
const moudleRef = ref<(DefineComponent & TestFormInstance) | null>(null);
const index = ref(0);

// const SEND_TEST_CMD_KEY = "send-test-cmd"; // 协商好的字符串Key
// const GET_TEST_DATA_KEY = "get-test-data"; // 配套的“获取数据”Key

const sendTestCmd = ref<(cmd: string, cmdParams?: any) => any>();
const getTestData = ref<any>();

// 在setup中立即提供这些引用
provide(SEND_TEST_CMD_KEY, sendTestCmd);
provide(GET_TEST_DATA_KEY, getTestData);

// 任务模块加载函数（支持插件命名机制）
const importMoudule = async () => {
  const moduleName: string = '测试';
  try {

    const loadModulesInstance = new LoadModules();
    const module = await loadModulesInstance.loadModule(moduleName);

    // 尝试多种方式获取createTestModule
    createTestModule = module.createTestModule || module.default?.createTestModule || module.default;

    // 尝试多种方式获取TestForm，适配不同的模块导出结构
    TestForm.value = module.TestForm || module.default?.TestForm;

    console.log(`测试模块[${moduleName}]加载成功`, { createTestModule, TestForm: module.TestForm });

  } catch (e) {
    console.error(`测试模块[${moduleName}]加载失败`, e);
  }
};

const loadModule = async () => {
  if (!createTestModule) {
    console.error("createTaskModule 未加载完成");
    return;
  }

  console.log("route.query.taskId", route.query.taskId);
  // 1. EventData 初始值：
  const initialTestData = {
    taskId: route.query.taskId || ""
  };

  // 2. 平台命令处理：完全转发插件传递的所有参数，对齐 createPost 逻辑
  const handleModuleCmd: SendCmd<{
    moduleId: string;
    fixedParams?: any;
    data?: Record<string, any>;
    params?: any;
    config?: AxiosRequestConfig;
  }, Response<any>> = async (moduleName, cmd, cmdParams) => {
    if (moduleName !== "TestForm") return { code: 400, msg: "模块不匹配", data: null };

    console.log("来自插件的请求--TestForm");
    console.log("平台接收测试指令：", cmd, cmdParams);

    const { commandName, command } = cmdParams?.fixedParams || {};

    const unifiedCommand = commandName || command || "";

    let url = `/api/Test/SendCommand`;
    if (unifiedCommand === "OpenTask") {
      url = `/api/Test/OpenTask`;
    } else if (unifiedCommand === "CloseTask") {
      url = `/api/Test/CloseTask`;
    }

    // 直接调用平台的 handlePluginCommand，传递所有参数（复刻 createPost 逻辑）
    return handleCommand(
      url, // url
      cmdParams?.fixedParams, // 固定参数（对齐 createPost 的 fixedParams）
      cmdParams?.data, // 业务数据（对齐 createPost 的 data）
      cmdParams?.params, // URL 参数（对齐 createPost 的 params）
      cmdParams?.config // Axios 配置（对齐 createPost 的 config）
    );
  };

  // 3. 创建插件实例：完全对齐原有调用方式
  const testModule: ModuleInterfaceTest<typeof initialTestData> = createTestModule(
    handleModuleCmd,
    initialTestData,
    updateState
  );

  // 关键：更新响应式引用，而不是重新提供
  sendTestCmd.value = (cmd: string, cmdParams?: any) => {
    return testModule.sendCommand(cmd, cmdParams);
  };
  getTestData.value = () => testModule.eventData;

  // 5. 手动初始化插件
  await testModule.startup();

  isComponentLoaded.value = true;
}

onMounted(async () => {

  await importMoudule();
  console.log("createTaskModule", createTestModule, "TestForm", TestForm);
  loadModule();
  (moudleRef.value as any)?.dataEvent(index.value);
})

/**
 * @description: 事件接收
 * @return {*}
 */
const initEvent = () => {
  const route = useRoute()
  const taskId = route.query?.taskId || "";
  signalEvent.$on(taskId as string, handleEvent);
};
const unloadEvent = () => {
  const route = useRoute()
  const taskId = route.query?.taskId || "";
  signalEvent.$off(taskId as string, handleEvent); // 卸载事件
};

type EventData = { dataName?: string; data: any };
const eventData = ref<EventData | undefined>();
const handleEvent = (param: EventData) => {
  console.log("param", param);
  eventData.value = param;
  (moudleRef.value as any)?.dataEvent(param);
}

onMounted(() => {
  initEvent();
})

onUnmounted(() => {
  unloadEvent();
})


</script>

<style lang="scss" scoped>
.test-view {
  height: 100%;
  overflow: auto;
  background-color: rgb(255, 255, 255);

  /* 美化原生滚动条（仅影响当前容器） */
  &::-webkit-scrollbar {
    width: 6px;
    /* 纵向滚动条宽度 */
    height: 6px;
    /* 横向滚动条高度 */
  }

  /* 滚动条轨道 */
  &::-webkit-scrollbar-track {
    background: transparent;
    /* 轨道透明，避免干扰子组件 */
  }

  /* 滚动条滑块 */
  &::-webkit-scrollbar-thumb {
    background: rgba(144, 147, 153, 0.3);
    /* 浅灰色半透明 */
    border-radius: 3px;
    /* 圆角 */
    transition: background 0.2s;
  }

  /* 滑块hover效果 */
  &::-webkit-scrollbar-thumb:hover {
    background: rgba(144, 147, 153, 0.6);
  }

  /* 隐藏横向滚动条（如果不需要） */
  &::-webkit-scrollbar-horizontal {
    display: none;
  }
}
</style>
